<template>
  <el-card>
    <div class="header">
      <h3>通知与提醒</h3>
      <el-space class="button-group">
        <el-button type="primary" @click="showSendDialog = true">发送通知</el-button>
        <el-button type="info" @click="fetchSentNotifications">我发送的通知</el-button>
      </el-space>
    </div>

    <el-button class="static-button" disabled>
      我收到的通知 (未读: {{ unreadCount }})
    </el-button>

    <el-table v-loading="loading" :data="notifications" stripe>
      <el-table-column prop="type" label="通知类型" width="120" />
      <el-table-column prop="content" label="内容" />
      <el-table-column prop="time" label="时间" width="180" />
      <el-table-column prop="sender" label="发送者" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
            :type="row.isRead ? 'info' : 'primary'"
            :disabled="row.isRead"
            size="small"
            @click="markAsRead(row)"
          >
            {{ row.isRead ? '已读' : '标记已读' }}
          </el-button>
          <el-button type="danger" size="small" @click="removeNotification(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 发送通知弹窗 -->
    <el-dialog v-model="showSendDialog" title="发送通知" width="600px">
      <el-form :model="newNotification" label-width="100px">
        <el-form-item label="通知内容" prop="content" required>
          <el-input
            v-model="newNotification.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
            clearable
          />
        </el-form-item>

        <el-form-item label="通知类型" prop="type" required>
          <el-select
            v-model="newNotification.type"
            placeholder="请选择通知类型"
            style="width: 100%"
            clearable
          >
            <el-option label="审批通知" :value="1" />
            <el-option label="提醒通知" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="接收范围" prop="target" required>
          <el-select
            v-model="newNotification.target"
            placeholder="选择接收范围"
            style="width: 100%"
            @change="handleTargetChange"
          >
            <el-option label="全体员工" value="all" />
            <el-option label="选择员工" value="specific" />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="newNotification.target === 'specific'"
          label="选择员工"
          prop="specificUsers"
          required
        >
          <el-select
            v-model="newNotification.specificUsers"
            placeholder="请选择员工"
            multiple
            style="width: 100%"
            filterable
            v-loading="loadingEmployees"
          >
            <el-option
              v-for="user in allEmployees"
              :key="user.id"
              :label="`${user.name || '未知'} (${user.role || '员工'})`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showSendDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="sendNewNotification"
          :loading="sending"
        >
          发送
        </el-button>
      </template>
    </el-dialog>

    <!-- 我发送的通知弹窗 -->
    <el-dialog v-model="showSentDialog" title="我发送的通知" width="800px">
      <el-table :data="sentNotifications" height="400" border>
        <el-table-column prop="content" label="内容" min-width="200" />
        <el-table-column prop="time" label="发送时间" width="180" />
      </el-table>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import {
  getNotificationList,
  markNotificationAsRead,
  deleteNotification,
  getUnreadNotifications,
  sendNotification,
  getSentNotifications
} from '@/api/notification'
import { getUserInfo, getEmployeeInfo } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据状态
const notifications = ref([])
const sentNotifications = ref([])
const allEmployees = ref([])
const loading = ref(false)
const loadingEmployees = ref(false)
const sending = ref(false)
const unreadCount = ref(0)
const showSendDialog = ref(false)
const showSentDialog = ref(false)

// 表单数据
const newNotification = ref({
  content: '',
  target: 'all',
  type: null,
  specificUsers: []
})

// 通知类型映射
const typeMap = {
  approval: '审批通知',
  reminder: '提醒通知',
  system: '系统通知'
};


// 获取所有员工信息
const fetchAllEmployees = async () => {
  loadingEmployees.value = true
  try {
    const response = await getEmployeeInfo()
    console.log('员工数据:', response) // 调试用

    // 根据实际API返回结构调整这里
    let employeeList = []
    if (Array.isArray(response?.data)) {
      employeeList = response.data
    } else if (response?.data?.list) {
      employeeList = response.data.list
    } else if (response?.data?.data) {
      employeeList = response.data.data
    } else if (response?.data) {
      // 如果data是对象而非数组
      employeeList = Object.values(response.data)
    }

    allEmployees.value = employeeList.map(user => ({
      id: user.id || user.userId,
      name: user.name || user.username || user.realName || '未知',
      role: user.role || user.position || '员工'
    }))

    console.log('处理后的员工列表:', allEmployees.value) // 调试用
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  } finally {
    loadingEmployees.value = false
  }
}

// 接收范围变更处理
const handleTargetChange = async (value) => {
  if (value === 'specific' && allEmployees.value.length === 0) {
    await fetchAllEmployees()
  }
}

// 获取通知列表
const fetchNotifications = async () => {
  loading.value = true;
  try {
    const response = await getNotificationList();
    if (response?.data?.code === 200) {
      const notificationData = response.data.data;

      // 获取所有发送者信息
      const senderRequests = notificationData.map(item =>
        getUserInfo(item.authorId).catch(() => null)
      );
      const senderResponses = await Promise.all(senderRequests);

      // 处理通知数据
      notifications.value = notificationData.map((item, index) => {
        const senderInfo = senderResponses[index]?.data?.data || {};
        const typeKey = isNaN(item.type) ? item.type : Number(item.type);  // 🔥 兼容数字和字符串
        return {
          id: item.id,
          type: typeMap[typeKey] || `未知类型(${item.type})`,  // ✅ 确保正确映射
          content: item.content || '暂无内容',
          time: item.createdAt ? dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss') : '未知时间',
          sender: senderInfo.username || '未知发送者',
          isRead: item.isRead === 1,
        };
      });

      // 更新未读计数
      await fetchUnreadNotifications();
    }
  } catch (error) {
    console.error('获取通知列表失败:', error);
    ElMessage.error('获取通知列表失败');
  } finally {
    loading.value = false;
  }
};



// 获取未读通知数量
const fetchUnreadNotifications = async () => {
  try {
    const response = await getUnreadNotifications()
    if (response?.data?.code === 200) {
      unreadCount.value = response.data.data.length
    }
  } catch (error) {
    console.error('获取未读通知失败:', error)
    ElMessage.error('获取未读通知失败')
  }
}

// 标记通知为已读
const markAsRead = async (row) => {
  if (row.isRead) return

  try {
    const response = await markNotificationAsRead(row.id)
    if (response?.data?.code === 200) {
      row.isRead = true
      unreadCount.value--
      ElMessage.success('已标记为已读')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

// 删除通知
const removeNotification = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const response = await deleteNotification(id)
    if (response?.data?.code === 200) {
      ElMessage.success('删除成功')
      fetchNotifications()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知失败:', error)
      ElMessage.error('删除通知失败')
    }
  }
}

// 发送新通知
const sendNewNotification = async () => {
  if (!newNotification.value.content.trim()) {
    return ElMessage.warning('请输入通知内容');
  }
  if (!newNotification.value.type) {
    return ElMessage.warning('请选择通知类型');
  }
  if (newNotification.value.target === 'specific' && newNotification.value.specificUsers.length === 0) {
    return ElMessage.warning('请选择员工');
  }

  sending.value = true;
  try {
    const { target, type, content, specificUsers } = newNotification.value;
    const data = { type, content };

    let targetParam = 0;
    if (target === 'all') {
      targetParam = 0;
    } else if (target === 'specific') {
      targetParam = 2;
      for (const userId of specificUsers) {
        data.userId = userId;  // 逐个传递用户 ID
        const response = await sendNotification(targetParam, data);

        if (response?.data?.code !== 200) {
          throw new Error('发送通知失败');
        }
      }
      ElMessage.success('通知发送成功');
      showSendDialog.value = false;

      // 重置表单
      newNotification.value = {
        content: '',
        target: 'all',
        type: null,
        specificUsers: []
      };

      // 刷新通知列表
      await fetchNotifications();
      return;
    } else {
      ElMessage.warning('请选择正确的发送目标');
      return;
    }

    // 发送给所有员工时只发送一次请求
    const response = await sendNotification(targetParam, data);
    if (response?.data?.code === 200) {
      ElMessage.success('通知发送成功');
      showSendDialog.value = false;

      // 重置表单
      newNotification.value = {
        content: '',
        target: 'all',
        type: null,
        specificUsers: []
      };

      await fetchNotifications();
    } else {
      ElMessage.error('通知发送失败');
    }
  } catch (error) {
    console.error('❌ 发送通知失败:', error);
    ElMessage.error('发送通知失败');
  } finally {
    sending.value = false;
  }
};






// 获取已发送通知
const fetchSentNotifications = async () => {
  try {
    const response = await getSentNotifications()
    if (response?.data?.code === 200) {
      sentNotifications.value = response.data.data.map(item => ({
        content: item.content,
        time: item.createdAt ? dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss') : '未知时间'
      }))
    }
    showSentDialog.value = true
  } catch (error) {
    console.error('获取已发送通知失败:', error)
    ElMessage.error('获取已发送通知失败')
  }
}

// 初始化加载
onMounted(() => {
  fetchNotifications()
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.static-button {
  margin-bottom: 20px;
  width: 20%;
}
</style>
